package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /*
        添加分类
     */
    @PostMapping
    public R save(@RequestBody Category category){
        categoryService.save(category);
        return R.success(null);
    }

    /*
        分页查询
     */
    @GetMapping("/page")
    public R<Page> page(Integer page,Integer pageSize){
        //排序条件
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByDesc(Category::getSort);
        //分页条件
        Page<Category> pageInfo = new Page<>(page, pageSize);
        categoryService.page(pageInfo,lambdaQueryWrapper);
        return R.success(pageInfo);
    }
    /*
        删除分类
     */
    @DeleteMapping
    public R deleteById(Long id){
        //要删除套餐分类或者菜品分类 的时候，先查询一下该分类下是否有关联菜品和套餐。有，就不删，并抛出业务异常。
        categoryService.removeById(id);
        //查询菜品分类是否关联菜品表
        //查询套餐分类是否关联套餐表
        //删除分类
        //业务比较复杂，会在service层专门写一个方法来处理这个复杂的业务。
        return R.success(null);
    }
    /*
        修改分类
     */
    @PutMapping
    public R update(@RequestBody Category category){
        categoryService.updateById(category);
        return R.success(null);
    }

    /*
        根据type查询所有的分类
        添加菜品   /category/list?type=1
        添加套餐   /category/list?type=2
        手机端 /category/list
     */
    @GetMapping("/list")
    public R<List<Category>> list(Integer type){
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(type!=null,Category::getType,type);
        //select * from category where type is null
        List<Category> list = categoryService.list(lambdaQueryWrapper);
        return R.success(list);
    }
}
